<template>
  <div class="system-user-dialog-container">
    <el-dialog :title="state.dialog.title" v-model="state.dialog.isShowDialog" width="600" top="5vh">
      <el-form ref="formRef" :model="state.ruleForm" :rules="state.rules" size="default" label-width="100px">
        <el-form-item label="姓名" prop="name">
          <el-input v-model="state.ruleForm.name" placeholder="请输入" clearable></el-input>
        </el-form-item>
        <el-form-item label="角色" prop="role_id">
          <CommonSelect v-model="state.ruleForm.role_id" placeholder="请选择" clearable class="w100"
            :options="state.roleList"></CommonSelect>
        </el-form-item>
        <el-form-item label="登陆账号" prop="username">
          <el-input v-model.trim="state.ruleForm.username" placeholder="请输入" maxlength="16" :disabled="isEdit">
          </el-input>
        </el-form-item>
        <el-form-item v-if="!isEdit" label="登录密码" prop="password">
          <el-input v-model.trim="state.ruleForm.password" placeholder="请输入" type="password"></el-input>
        </el-form-item>
        <el-form-item label="手机号" prop="mobile">
          <el-input v-model="state.ruleForm.mobile" placeholder="请输入手机号" maxlength="11"></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="state.ruleForm.email" placeholder="请输入"></el-input>
        </el-form-item>
        <el-form-item label="性别" prop="gender">
          <el-radio-group v-model="state.ruleForm.gender">
            <el-radio label="MALE">男</el-radio>
            <el-radio label="FEMALE">女</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="用户状态" prop="disabled">
          <el-radio-group v-model="state.ruleForm.disabled">
            <el-radio :label="false">启用</el-radio>
            <el-radio :label="true">禁用</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="onCancel" size="default">取 消</el-button>
          <el-button type="primary" @click="onSubmit" size="default" :loading="state.submit.loading">保存</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts" name="systemUserDialog">
import { nextTick, reactive, ref } from 'vue';
import CommonSelect from '/@/components/common-select/index.vue';
import { verifyPasswordPowerful, verifyPhone } from '/@/utils/tools-validate';
import { readAllRole } from '/@/api/role';
import { Role, User } from '/@/models';
import { DialogType } from '/@/constants/dialog-type';
import { createUser, updateUser } from '/@/api/user';
import { ElMessage } from 'element-plus';
import { createPassword } from '/@/utils/createPassword';
import { computed } from 'vue';
import { assginDefault } from '/@/utils/assign-default';
import { createRequiredRule } from '/@/utils';
import { Gender } from '/@/constants';
import { arrayToOptions } from '/@/utils/array-to-options';

// 定义子组件向父组件传值/事件
const emit = defineEmits(['refresh']);

// 定义变量内容
const formRef = ref();
const state = reactive({
  id: '',
  ruleForm: {
    username: '', // 账户名称
    name: '', // 用户昵称
    role_id: '', // 关联角色
    mobile: '', // 手机号
    email: '', // 邮箱
    gender: Gender.MALE, // 性别
    password: '', // 账户密码
    disabled: false // 用户状态
  },
  rules: {
    username: [createRequiredRule(), { type: 'string', min: 5, max: 16, message: '登陆账户长度为5到16位' }],
    name: [createRequiredRule()],
    role_id: createRequiredRule(),
    mobile: [
      createRequiredRule(),
      {
        validator: (_: any, value: string, callback: any) => {
          if (verifyPhone(value)) {
            callback();
          } else {
            callback(new Error('手机号格式错误'));
          }
        }
      }
    ],
    email: { type: 'email', message: '邮箱格式错误' },
    password: [
      createRequiredRule(),
      {
        validator: (_: any, value: string, callback: any) => {
          if (verifyPasswordPowerful(value)) {
            callback();
          } else {
            callback(new Error('手机号格式错误'));
          }
        },
        message: '密码为6到16位，且必须包含字母数字和特殊字符'
      }
    ],
    gender: createRequiredRule()
  },
  roleList: [],
  submit: {
    loading: false
  },
  dialog: {
    isShowDialog: false,
    type: '',
    title: ''
  }
});

const isEdit = computed(() => {
  return state.dialog.type === DialogType.EDIT;
});

const getRoleList = async () => {
  const data = await readAllRole();
  state.roleList = arrayToOptions("description", "id", data);
};


// 打开弹窗
const openDialog = (type: string, row?: User) => {
  state.dialog.type = type;
  state.dialog.isShowDialog = true;
  nextTick(() => {
    if (type === DialogType.EDIT) {
      state.id = row.id;
      assginDefault(state.ruleForm, row);
      if(row.roles && row.roles.length > 0) {
        state.ruleForm.role_id = row.roles[0].id;
      }
      state.dialog.title = '修改人员';
    } else {
      state.id = '';
      state.dialog.title = '新增人员';
      formRef.value?.resetFields();
    }
  });

  if (!state.roleList.length) {
    getRoleList();
  }
};

// 关闭弹窗
const closeDialog = () => {
  state.dialog.isShowDialog = false;
};

// 取消
const onCancel = () => {
  closeDialog();
};

// 提交
const onSubmit = async () => {
  await formRef.value.validate();
  try {
    state.submit.loading = true;
    const data = state.ruleForm

    if(state.role_id) {
      data.role = [{id: state.role_id}]
    }

    if (state.dialog.type === DialogType.EDIT) {
      await updateUser(state.id, data);
    } else {
      await createUser(data);
    }
    ElMessage.success('保存成功');
    closeDialog();
    emit('refresh');
  } catch (err) {
    console.log(err);
  }

  state.submit.loading = false;
};

// 暴露变量
defineExpose({
  openDialog,
  closeDialog
});
</script>
